iT邦幫忙

2023 iThome 鐵人賽

DAY 8
0
Software Development

LELECOCODE 每一天系列 第 8

Day 8 : Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 8: Function Composition

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions.

The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).

The function composition of an empty list of functions is the identity function f(x) = x.

You may assume each function in the array accepts one integer as input and returns one integer as output.

var compose = function(functions) {
	return function(x) {
        
    }
};

Example 1:
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
Output: 65

Example 2:
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1
Output: 1000

Example 3:
Input: functions = [], x = 42
Output: 42


這題蠻燒腦的,一開始有點打結,困難點在於裡面原本寫死的 return function(x){}
不過想通後,就有種打通的感覺,但是後面一直卡在 case 1,卡了一陣子,怎麼算都是 50,不是 65 呀。
後來多學了一招 reduceRight 是從右至左的方法,就對了,如下:

var compose = function(functions) {
	return function(x) {
        return functions.reduce((result, fn) => fn(result), x)
    };
};

改用 reduceRight

var compose = function(functions) {
	return function(x) {
        return functions.reduceRight((result, fn) => fn(result), x)
    };
};

上一篇
Day7 : Leetcode 小挑戰,30 Days of JavaScript
下一篇
Day 9 : Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言